package cn.xsw.controller;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import cn.xsw.common.JwtTokenUtil;
import cn.xsw.common.ResultBody;
import cn.xsw.entity.User;
import cn.xsw.entity.vo.UserVo;
import cn.xsw.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liangYiHui
 * @since 2021-06-14
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation("登录(参数UserInfo,由wx.getUserProfile获,code属性由wx.login)")
    @PostMapping("/login")
    public ResultBody login(@RequestBody UserVo user){
        Object forObject = new RestTemplate()
                .getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=wx91ad32f9cb294223&secret=e17e0a5a1cd5d44eb15f3cf6f86d5b43&js_code="+user.getCode()+"&grant_type=authorization_code"
                        , Object.class);
        String s = JSONUtil.toJsonStr(forObject);
        return ResultBody.success("测试"+s);
    }
    @ApiOperation("管理员登录，返回X-TOKEN")
    @GetMapping("/adminLogin")
    public ResultBody adminLogin(String username,String password){
        if(username==null||password==null) return ResultBody.error("用户名和密码为必填项");
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("username", username).eq("password", SecureUtil.md5(password));
        User user = userService.getOne(wrapper);
        if(user==null) return  ResultBody.error("用户名或密码错误");
        String token = JwtTokenUtil.generateToken(user);
        return ResultBody.success(token).setMessage("登录成功");

    }
}

